<template>
  <div>
    <!-- Breadcrumb面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bottomborder', i1 === 0 ? 'upborder' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightRolseById(scope.row, item1.id)"
                  >{{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 渲染二级三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'upborder', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightRolseById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightRolseById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="400px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="closeDefKeys"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="righstList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],

      // 设置分配权限
      setRightDialogVisible: false,

      // 权限列表
      righstList: [],

      // 树形控件的属性绑定对象
      treeProps: {
        label: "authName",
        children: "children",
      },
      // 默认选中的结点ID值数组
      defKeys: [],
      // 分配的角色权限
      rightKeys:[],
      // 角色id
      nodeId:''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 加载角色列表
    async getRolesList() {
      const { data: res } = await this.$axios.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.rolesList = res.data;
      // console.log(this.rolesList);
    },

    // 通过id来删除角色权限
    async removeRightRolseById(role, rightId) {
      // 弹出框提示确认是否删除
      const removeResult = await this.$confirm(
        "此操作将永久删除, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (removeResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      // console.log("确认已删除");
      const { data: res } = await this.$axios.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) {
        return console.log("删除角色指定权限失败");
      }
      // 会导致整个页面重新刷新，用户体验感不好。
      // this.getRolesList();
      // console.log(res);
      // 返回的data, 是当前角色下最新的权限数据
      role.children = res.data;
    },

    // 弹出设置权限对话框
    async showSetRightDialog(node) {
      
      this.nodeId=node.id;
      // 获取角色权限数据
      const { data: res } = await this.$axios.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限列表失败");
      }
      // console.log(res.data);
      // 将获取的数据保存到rightsList数组中
      this.righstList = res.data;
      this.getLeafKeys(node, this.defKeys);
      this.setRightDialogVisible = true;
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到defkeys数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        // 如果没有三级节点，就把ID存到数组arr中
        return arr.push(node.id);
      }

      // 如果存在孩子结点，则进行递归
      node.children.forEach((element) => {
        this.getLeafKeys(element, arr);
      });
    },

    //当树形对话框关闭后，defKeys数组需要清空
    closeDefKeys() {
      this.defKeys = [];
    },

    // 点击分配权限
    async allotRights() {
      // 获取到所有被选中的叶子结点，以及半选中的结点key
      const keys=[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      
      // 以逗号隔开数组
      this.rightKeys=keys.join(',');
      // 向服务器发送post请求
      const {data:res}= await this.$axios.post(`roles/${this.nodeId}/rights`,{rids:this.rightKeys});
      if(res.meta.status!==200){
        return this.$message.error("分配用户权限失败");
      }
      // 关闭树形弹框
      this.$message.success("分配用户权限成功");
      // 还需要重新刷新一下数据列表
      this.getRolesList();
      this.setRightDialogVisible=false;
    },
  },
};
</script>

<style scope>
.el-tag {
  margin: 7px;
}
.upborder {
  border-top: solid 1px#eee;
}
.bottomborder {
  border-bottom: solid 1px#eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>